package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;





    @Override
    public Result queryShopById(Long id) {
        //从Redis缓存中获取店铺信息，转成JSON字符串返回
        String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
        //判断缓存中是否有店铺信息
        if(StrUtil.isNotBlank(shopJson)){
            //有缓存，直接返回缓存中的店铺信息
            //转成json字符串返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);


            return Result.ok(shop);
        }
        //缓存中没有店铺信息，从数据库中查询
        Shop shop = getById(id);

        //判断是否查询到店铺信息
        if(shop == null){
            return Result.fail("店铺信息不存在");
        }

        //将店铺信息转成JSON字符串，存入Redis缓存
        stringRedisTemplate.opsForValue().set("cache:shop:" + id, JSONUtil.toJsonStr(shop));
        return Result.ok(shop);



    }

    //修改店铺信息
    @Override
    @Transactional
    public Result update(Shop shop) {

        Long id = shop.getId();

        //判断店铺名称是否为空
        if(id == null){
            return Result.fail("店铺ID不能为空");
        }
        //修改数据库中的店铺信息
        boolean update = updateById(shop);
        //判断是否修改成功
        if(update){
            //修改成功，删除Redis缓存中的店铺信息
            stringRedisTemplate.delete("cache:shop:" + shop.getId());
            return Result.ok();
        }
        return Result.fail("修改失败"); //修改失败
    }
}
